package com.qire.manhua.model.viewModel.impl;

import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.ComicDetailIntroductionController;
import com.qire.manhua.databinding.LayoutComicDetailCommentItemBinding;
import com.qire.manhua.databinding.LayoutComicDetailRecommendLikeItemBinding;
import com.qire.manhua.databinding.LayoutComicDetailRecommendRankItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicComment;
import com.qire.manhua.dal.service.ComicDetailIntroductionService;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

public class ComicDetailIntroductionViewModel extends BaseViewModel {

    private final ComicDetailIntroductionService introductionService = new ComicDetailIntroductionService(this);

    private final ArrayList<ComicDetailCommentItemViewModel> commentItemViewList = ListUtil.newArrayList();
    private final ArrayList<ComicDetailRecommendRankItemViewModel> recommendRankItemViewList = ListUtil.newArrayList();
    private final ArrayList<ComicDetailRecommendLikeItemViewModel> recommendLikeItemViewList = ListUtil.newArrayList();

    private final SummerBindAdapter<ComicDetailCommentItemViewModel> commentAdapter = new SummerBindAdapter<>(commentItemViewList);
    private final SummerRecyclerBindAdapter<ComicDetailRecommendRankItemViewModel> recommendRankAdapter = new SummerRecyclerBindAdapter<>(recommendRankItemViewList);
    private final SummerRecyclerBindAdapter<ComicDetailRecommendLikeItemViewModel> recommendLikeAdapter = new SummerRecyclerBindAdapter<>(recommendLikeItemViewList);

    private int rankTypeId;
    private ComicBookEntity comicBookEntity;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicDetailIntroductionController controller) {
        this.commentAdapter.setEventProcess(controller);
        this.recommendRankAdapter.setEventProcess(controller);
        this.recommendLikeAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.comicBookEntity = null;
        this.commentAdapter.setEventProcess(null);
        this.recommendRankAdapter.setEventProcess(null);
        this.recommendLikeAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    public void loadComicBookEntity(ComicBookEntity comicBookEntity) {
        this.comicBookEntity = comicBookEntity;
        loadRandomRecommend();
    }

    public void loadRandomRecommend() {
        if(ObjectUtil.nonNull(comicBookEntity)) {
            introductionService.randomRecommend(comicBookEntity.id);
        }
    }

    public ComicBookEntity comicBookEntity() {
        return comicBookEntity;
    }

    public void loadComicUpdateInfo(CharSequence updateStateInfo) {
        String updateStateInfoText;
        if(comicBookEntity.isEndState()) {
            updateStateInfoText = "已完结";
        } else {
            updateStateInfoText = StringUtil.isEmpty(updateStateInfo) ? "连载中" : String.format("连载中 · %s", updateStateInfo);
        }
        put("updateStateInfo", updateStateInfoText);
    }

    /**
     * 加载统计信息
     * @param popularCount 人气统计数
     * @param likesCount 点赞统计数
     * @param favoritesCount 收藏统计数
     * @param commentCount 评论统计数
     */
    public void loadCountInfo(int popularCount, int likesCount, int favoritesCount, int commentCount) {
        put("popularCountText", StringUtil.toSymbol(popularCount));
        put("likesCountText", StringUtil.toSymbol(likesCount));
        put("favoritesCountText", StringUtil.toSymbol(favoritesCount));
        put("moreCommentBtnText", "查看所有评论("+commentCount+")");
    }

    public void setComicBookIntroduction(CharSequence comicBookIntroduction) {
        put("comicBookIntroduction", comicBookIntroduction);
    }

    public void setComicBookCopyrightsInfo(CharSequence comicBookCopyrightsInfo) {
        put("comicBookCopyrightsInfo", comicBookCopyrightsInfo);
    }

    /**
     * 加载评论信息
     * @param comments 漫画评论
     */
    public void loadComicComment(ComicComment[] comments) {
        commentItemViewList.clear();
        for(ComicComment comment : comments) {
            commentItemViewList.add(new ComicDetailCommentItemViewModel(comment));
        }
        commentAdapter.notifyDataSetChanged();

        boolean isEmptyData = ListUtil.isEmpty(commentItemViewList);
        put("commentListVisible", isEmptyData ? View.GONE : View.VISIBLE);
        put("noCommentPanelVisible", isEmptyData ? View.VISIBLE : View.GONE);
    }

    public void loadRankInfo(String rankTitle, int rankTypeId) {
        this.rankTypeId = rankTypeId;
        put("rankTitle", rankTitle);
    }

    public int rankTypeId() {
        return rankTypeId;
    }

    /**
     * 清理排行榜数据列表
     */
    public void clearRankList(){
        recommendRankItemViewList.clear();
    }

    /**
     * 添加排行榜数据项
     * @param rankIndex 排序
     */
    public void addRankItemViewModel(int rankIndex, int bookId, String bookName, String coverImg, String[] tags) {
        recommendRankItemViewList.add(new ComicDetailRecommendRankItemViewModel(rankIndex, bookId, bookName, coverImg, tags));
    }

    /**
     * 刷新排行榜数据UI显示
     */
    public void refreshRankAdapter(){
        recommendRankAdapter.notifyDataSetChanged();
    }

    /**
     * 清理猜你喜欢项目数据
     */
    public void clearLikeList() {
        recommendLikeItemViewList.clear();
    }

    /**
     * 添加猜你喜欢项目数据
     * @param serialNumber 排序
     */
    public void addLikeItemViewModel(int serialNumber, int bookId, String bookName, String coverImg, String[] tags) {
        recommendLikeItemViewList.add(new ComicDetailRecommendLikeItemViewModel(serialNumber, bookId, bookName, coverImg, tags));
    }

    /**
     * 刷新猜你喜欢数据UI显示
     */
    public void refreshLikeAdapter(){
        recommendLikeAdapter.notifyDataSetChanged();
    }

    public BaseAdapter getCommentAdapter() {
        return commentAdapter;
    }

    public Adapter getRecommendRankAdapter() {
        return recommendRankAdapter;
    }

    public Adapter getRecommendLikeAdapter() {
        return recommendLikeAdapter;
    }

    public LayoutManager getRecommendLikeLayoutManager() {
        return new GridLayoutManager(null, 3, GridLayoutManager.VERTICAL, false);
    }

    public MutableLiveData<CharSequence> getUpdateStateInfo() {
        return get("updateStateInfo");
    }

    public MutableLiveData<CharSequence> getComicBookIntroduction() {
        return get("comicBookIntroduction");
    }

    public MutableLiveData<CharSequence> getPopularCountText() {
        return get("popularCountText");
    }

    public MutableLiveData<CharSequence> getLikesCountText() {
        return get("likesCountText");
    }

    public MutableLiveData<CharSequence> getFavoritesCountText() {
        return get("favoritesCountText");
    }

    public MutableLiveData<Integer> getCommentListVisible() {
        return get("commentListVisible");
    }

    public MutableLiveData<Integer> getNoCommentPanelVisible() {
        return get("noCommentPanelVisible");
    }

    public MutableLiveData<CharSequence> getMoreCommentBtnText() {
        return get("moreCommentBtnText");
    }

    public MutableLiveData<CharSequence> getRankTitle() {
        return get("rankTitle");
    }

    public MutableLiveData<CharSequence> getComicBookCopyrightsInfo() {
        return get("comicBookCopyrightsInfo");
    }


    @AdapterEntityBind(viewRid = R.layout.layout_comic_detail_comment_item)
    public class ComicDetailCommentItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDetailCommentItemBinding> {

        private final ComicComment comicComment;

        public ComicDetailCommentItemViewModel(ComicComment comicComment) {
            this.comicComment = comicComment;
        }

        public ComicComment comicComment() {
            return comicComment;
        }

        public void voteToGiveLike() {
            introductionService.voteToGiveLikeComment(comicBookEntity.id, comicComment.id);
            comicComment.likeCountUp();
            notifyPropertyChanged(BR.thumbsUpRes);
            notifyPropertyChanged(BR.likeCount);
        }

        /**
         * 举报
         * @param type 举报类型
         * @param content 举报内容
         */
        public void complaint(int type, String content) {
            introductionService.complaintComment(comicBookEntity.id, comicComment.id, type, content);
        }

        public boolean isLike() {
            if(ObjectUtil.isNull(comicComment)) {
                return false;
            }
            return comicComment.isMyLike();
        }

        public String userName() {
            return this.comicComment.userName;
        }

        public String content() {
            return comicComment.content.toString();
        }

        @Override
        public void bindVariable(LayoutComicDetailCommentItemBinding viewBind) {
            viewBind.setComicDetailCommentItemViewModel(this);
        }

        @Bindable
        public int getPortraitFloatIconVisible(){
            return comicComment.isVip() ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public String getPortraitPath() {
            return comicComment.userPortrait;
        }

        @Bindable
        public String getUserName(){
            return comicComment.userName;
        }

        @Bindable
        public String getUserNameColor(){
            return comicComment.isVip() ? "#ff5050" : "#777777";
        }

        @Bindable
        public CharSequence getContent() {
            return comicComment.content;
        }

        @Bindable
        public String getCreateTime(){
            return comicComment.createTime;
        }

        @Bindable
        public int getThumbsUpRes(){
            return comicComment.isMyLike() ? R.drawable.app_comic_detail_comment_icon_give_like_b : R.drawable.app_comic_detail_comment_icon_give_like_a;
        }

        @Bindable
        public String getLikeCount(){
            return StringUtil.toSymbol(comicComment.likeCount());
        }

        @Bindable
        public String getReplyCount(){
            return comicComment.replyCountToString();
        }

    }

    @AdapterEntityBind(viewRid = R.layout.layout_comic_detail_recommend_rank_item)
    public class ComicDetailRecommendRankItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDetailRecommendRankItemBinding> {

        private final int    rankIndex;

        public  final int    bookId;
        public  final String bookName;
        private final String coverImg;
        private final String tag;

        public ComicDetailRecommendRankItemViewModel(int rankIndex, int bookId, String bookName, String coverImg, String[] tags) {

            this.rankIndex  = rankIndex;

            this.bookId     = bookId;
            this.bookName   = bookName;
            this.coverImg   = coverImg;
            StringBuilder builder = new StringBuilder();
            for(String tag : tags) {
                builder.append(tag).append(" ");
            }
            this.tag        = builder.toString();
        }

        @Override
        public void bindVariable(LayoutComicDetailRecommendRankItemBinding viewBind) {
            viewBind.setComicDetailRecommendRankItemViewModel(this);
        }

        @Bindable
        public int getRankIcon(){
            switch (rankIndex) {
                case 1 :
                    return R.drawable.app_comic_detail_rank_icon_1;
                case 2 :
                    return R.drawable.app_comic_detail_rank_icon_2;
                case 3 :
                    return R.drawable.app_comic_detail_rank_icon_3;
                default:
                    return 0;
            }
        }

        @Bindable
        public String getCoverImg() {
            return coverImg;
        }
        @Bindable
        public String getTitle() {
            return bookName;
        }
        @Bindable
        public String getTag() {
            return tag;
        }

    }

    @AdapterEntityBind(viewRid = R.layout.layout_comic_detail_recommend_like_item)
    public class ComicDetailRecommendLikeItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDetailRecommendLikeItemBinding> {

        public final int serialNumber;

        public  final int    bookId;
        public  final String bookName;
        private final String coverImg;
        private final String tag;

        public ComicDetailRecommendLikeItemViewModel(int serialNumber, int bookId, String bookName, String coverImg, String[] tags) {
            this.serialNumber = serialNumber;
            this.bookId     = bookId;
            this.bookName   = bookName;
            this.coverImg   = coverImg;
            StringBuilder builder = new StringBuilder();
            for(String tag : tags) {
                builder.append(tag).append(" ");
            }
            this.tag        = builder.toString();
        }

        @Override
        public void bindVariable(LayoutComicDetailRecommendLikeItemBinding viewBind) {
            viewBind.setComicDetailRecommendLikeItemViewModel(this);
        }

        @Bindable
        public String getCoverImg() {
            return coverImg;
        }

        @Bindable
        public String getTitle() {
            return bookName;
        }

        @Bindable
        public String getTag() {
            return tag;
        }

    }

}
